package com.bjpowernode.handler;

import cn.hutool.json.JSONUtil;
import com.bjpowernode.result.Result;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 应用访问拒绝处理器
 * 实现AccessDeniedHandler接口，用于处理用户访问无权限资源时的业务逻辑
 * 主要功能：构建并返回包含权限不足信息的JSON响应
 */
@Component
public class AppAccessDeniedHandler implements AccessDeniedHandler {
    /**
     * 处理访问拒绝逻辑
     * @param request HTTP请求对象
     * @param response HTTP响应对象
     * @param accessDeniedException 访问拒绝异常对象
     * @throws IOException IO异常
     * @throws ServletException Servlet异常
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        // 设置响应内容类型为JSON格式，字符编码为UTF-8
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");

        // 构建权限不足响应结果
        // 状态码：401（未授权）
        // 消息内容：明确提示用户权限不足
        Result result = Result.builder().code(401).msg("权限不足").build();

        // 使用Hutool工具包将Result对象转换为JSON字符串
        String json = JSONUtil.toJsonStr(result);

        // 将JSON响应写入客户端
        response.getWriter().write(json);
    }
}
